package com.jeesite.modules.kj.utils;

import com.jeesite.common.utils.SpringUtils;
import com.jeesite.modules.kj.entity.*;
import com.jeesite.modules.kj.service.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

public class BadgeUtil {
    /**
     * 静态内部类，延迟加载，懒汉式，线程安全的单例模式
     */
    private static final class Static {
        private static KjMemberService kjMemberService = SpringUtils.getBean(KjMemberService.class);

        private static KjBadgeTypeService kjBadgeTypeService = SpringUtils.getBean(KjBadgeTypeService.class);
        private static KjMemberIntegralHistoryService kjMemberIntegralHistoryService = SpringUtils.getBean(KjMemberIntegralHistoryService.class);
        private static KjBadgeService kjBadgeService = SpringUtils.getBean(KjBadgeService.class);
        private static KjMemberBadgeService kjMemberBadgeService = SpringUtils.getBean(KjMemberBadgeService.class);
    }

    /**
     * 用户获取徽章
     */
    public static void gainBadge(KjMember kjMember, String jobTypeId){
        //查找用户该岗位下获得的所有积分
        KjMemberIntegralHistory history = new KjMemberIntegralHistory();
        history.setKjMember(kjMember);
        history.setJobTypeId(jobTypeId);
        BigDecimal jobIntegrals = Static.kjMemberIntegralHistoryService.getJobIntegrals(history);
        //获取该岗位类型所有徽章
        KjBadgeType type = new KjBadgeType();
        type.setJobTypeId(jobTypeId);
        KjBadge where = new KjBadge();
        where.setKjBadgeType(type);
        where.setLimitIntegral_lte(jobIntegrals);
        List<KjBadge> badges = Static.kjBadgeService.findList(where);
        for (KjBadge badge: badges
             ) {
            KjMemberBadge mb = new KjMemberBadge();
            mb.setKjBadge(badge);
            mb.setMemberId(kjMember.getId());
            long count = Static.kjMemberBadgeService.findCount(mb);
            if(count == 0){
                mb.setGatherTime(new Date());
                mb.setMemberName(kjMember.getName());
                Static.kjMemberBadgeService.save(mb);
            }
        }
    }
}
